package cn.itcast.controller;

import cn.itcast.pojo.Result;
import cn.itcast.utils.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/upload")
@Slf4j
public class UploadController {
    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    //上传到阿里云
    @PostMapping
    public Result upload(MultipartFile file) {

        try {
            String url = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
            return Result.success(url);
        } catch (Exception e) {
            throw new RuntimeException(e);

        }


    }


//    //上传到本地的文件夹
//    @PostMapping
//    public Result upload(MultipartFile file) throws Exception {
//        final String UPLOAD_DIR = "E:/images/";
//        if (!file.isEmpty()) {
//            //1.生成唯一文件名
//            String originalFilename = file.getOriginalFilename();
//            //截取后缀.xxx
//            String exName = originalFilename.substring(originalFilename.lastIndexOf("."));
//            String uniqueFileName = UUID.randomUUID().toString().replace("-", "") + exName;
//            //拼接完成路径
//            File targetFile = new File(UPLOAD_DIR + uniqueFileName);
//            //如果不存在，就创建
//            if (!targetFile.getParentFile().exists()) {
//                targetFile.getParentFile().mkdirs();
//            }
//            //保存文件
//            file.transferTo(targetFile);
//        }
//        return Result.success();
//    }
}
